<?php
namespace app\admin\controller;

use app\admin\library\AdminController;
use cubox\Cubox;
use cubox\Data;

class App extends AdminController{

    public function __construct()
    {
        parent::__construct();
        $this->power('admin.app');
    }

    public function onIndex(){
        $this->pageTitle = '应用列表';
        $this->pageIcon = 'fa-cube';
        return $this->display();
    }

    public function onList(){
        $path = ROOT.DS.APP;
         
        $list = [];
        $dirList = scandir($path);
        
        foreach($dirList as  $value){
            if ($value== '.' || $value== '..') continue;
            $appDirPath = $path.DS.$value;
            $info = [];
            if (is_dir($appDirPath)){
                $projectPath = $appDirPath.DS.'project.php';

                if (is_file($projectPath)){
                    $project = new Data($projectPath);
                    $project->read();

                    $app = $project->toArray();
                    $info['status'] = $app['status']??false;
                    $info['name'] = $app['name'];
                    $info['title'] = $app['title'];
                    $info['description'] = $app['description'];
                    $info['icon'] =  $this->assetUrl(ROOT. '/' . APP  . '/' . $app['name']. '/' . $app['icon']);
                    $info['version'] = $app['version'];
                    $info['author'] = $app['author'];

                    $databasePath = $appDirPath.DS.'_setup';
                    
                    if (is_dir($databasePath)){
                        $info['install'] =  true;
                    }else{
                        $info['install'] =  false;
                    }

                    $list [] = $info;
                }
            }
        }

        return $list;
    }

    public function onDatabaseConfigList(){
        $appName = $this->post('app',$this->check('App')->type('string')->required());
        $designerPath = ROOT.DS.APP.DS.$appName.DS.'_setup'.DS.'config.php';
        
        $driverList  = [];
        
        if (file_exists($designerPath)){
            $designer = new Data($designerPath);
            $designer->read();
            $driverList  = $designer->driverList;
        }

        if (count($driverList)==0){
            throw new \Exception('需要添加支持的数据库类型');
        }

        $configFile =  $this->getAppConfig($appName,'database')->toArray();
         
        $list = [];

        if (isset($configFile['default'])){

            $default =  $configFile['default'];

            if (isset($configFile[$default])){
                $config = $configFile[$default];
                 
                if (in_array($config['driver'],$driverList)){
                    $list [] = [
                        'label'=>'[默认]'.$this->frontTitle($config),
                        'value'=>'default',
                        'driver'=>$config['driver']
                    ];
                    unset($configFile[$default]);
                }
            }
        }
 
        foreach($configFile as $name => $config){
            if (is_array($config) && isset($config['driver']) && in_array($config['driver'],$driverList)){

                $list [] = [
                    'label'=>$this->frontTitle($config),
                    'value'=>$name,
                    'driver'=>$config['driver']
                ];

                $list[] = $this->frontTitle($config);
            }
        }
        

        //获取modelList
        $modelList = [];
        $projectPath = ROOT.DS.APP.DS.$appName.DS.'project.php';
        if (is_file($projectPath)){
            $project = new Data($projectPath);
            $project->read();
            
            foreach($project->model as $name => $model){
                $model['name'] = $name;
                $model['sql'] =  $this->getModelSQl($appName,$name);
                $modelList[] = $model;
            }
        }

        return ['config'=>$list,'model'=>$modelList];
    }


    public function onSetupDatabase(){
        $appName = $this->post('app',$this->check('App')->type('string')->required());
        $configName = $this->post('config',$this->check('Config')->type('string')->required());
        $modelList = $this->post('list',$this->check('Model')->type('array')->required());

        $appConfig = $this->getAppConfig($appName,'database');
        $projectPath = ROOT.DS.APP.DS.$appName.DS.'project.php';

        if (!file_exists($projectPath)) throw new \Exception('应用文件不存在');
        $project  = new Data($projectPath);
        $modelConfig = $project->model;
        $db = Cubox::db($configName,$appConfig);
        $driver = $db->getConfig()['driver'];
        foreach($modelList as $name){
            $path  = ROOT.DS.APP.DS.$appName.DS.'_setup'.DS.'model'.DS.$name.DS.strtolower($driver).'.sql';
            if (file_exists($path)){
                try{
                    $db->query(file_get_contents($path));
                    $modelConfig[$name]['config'] = $configName;
                }catch(\Exception $e){
                    throw new \Exception($e->getMessage());
                }
                
            }else{
                throw new \Exception($name.'SQL文件不存在');
            }
        }
        $project->model = $modelConfig;
        $project->save();

        return true;
    }


    public function onStatus(){
        $appName = $this->post('app',$this->check('App')->type('string')->required());
        $status = $this->post('status',$this->check('Status')->type('bool')->required());
        $projectPath = ROOT.DS.APP.DS.$appName.DS.'project.php';
        
        if (!file_exists($projectPath)) throw new \Exception('项目文件不存在');
        $project = new Data($projectPath);
        $project->read();

        

        if ($status){
            $app = Cubox::app($appName,$project->toArray());

            try{
                $app->checkSetup();
            }catch(\Exception $e){
                throw new \Exception($e->getMessage());
            }

            $modelList = $project->model;

            foreach($modelList as $name => $model){
                $obj = $app->model($name);

                try{
                    $obj->count();
                }catch(\Exception $e){
                    throw new \Exception($e->getMessage());
                }
            }
        }
        $project->status = $status;
        $project->save();

        $runPath = ROOT.DS.RUNTIME.'bi.php';

        if (file_exists($runPath)) unlink($runPath);
        return true;
    }


    private function frontTitle($config){
        $className ='\\cubox\\database\\'.ucfirst($config['driver']);
        if (class_exists($className)) return ucfirst($config['driver']).'-' . $className::frontTitle($config);
    }
    
    private function getAppConfig($app,$type):Data{
        $path  = ROOT.DS.CONFIG.DS.$app.DS.$type.'.php';

        if (file_exists($path)){
           return new Data($path);
        }else{
           return Cubox::config($type);
        }
    }

    private function getModelSQl($app,$name):array{
        $path  = ROOT.DS.APP.DS.$app.DS.'_setup'.DS.'model'.DS.$name;
        if (file_exists($path)){
            
            $sqlList = [];
            $dirList = scandir($path);
            foreach($dirList as $value){
                if ($value== '.' || $value== '..') continue;
                $sqlPath = $path.DS.$value;
                if (is_file($sqlPath) && strtolower(pathinfo($sqlPath,PATHINFO_EXTENSION))=='sql'){
                    $sqlList[] = strtolower(pathinfo($sqlPath,PATHINFO_FILENAME));
                }
            }
            return $sqlList;
        }else{
            return [];
        }
    }

    
}